<template>
  <div class="product-management-container">
    <!-- 搜索筛选区 -->
    <div class="filter-card">
      <el-form :model="filterForm" inline>
        <!-- 基础信息 -->
        <el-form-item label="产品ID">
          <el-input 
            v-model.number="filterForm.pid"   
            placeholder="ID" 
            clearable 
            @keyup.enter="handleSearch" 
            style="width: 70px;" 
          />
        </el-form-item>
 
        <el-form-item label="产品名称">
          <el-input 
            v-model="filterForm.name"   
            placeholder="输入名称" 
            clearable 
            @keyup.enter="handleSearch" 
            style="width: 120px" 
          />
        </el-form-item>
 
        <!-- 叉型选择 -->
        <el-form-item label="叉型">
          <el-select 
            v-model="filterForm.sidefork"   
            placeholder="选择叉型" 
            clearable 
            @change="handleForkTypeChange"
            style="width: 100px"
          >
            <el-option label="二面叉" :value="0" />
            <el-option label="四面叉" :value="1" />
          </el-select>
        </el-form-item>
 
        <!-- 板材类型 -->
        <el-form-item label="板材">
          <el-select v-model="filterForm.panel_Leg"  placeholder="选择板材" clearable style="width: 140px">
            <el-option label="板条-原木" :value="0" />
            <el-option label="胶合板-多层板" :value="1" />
          </el-select>
        </el-form-item>
 
        <!-- 动态字段 - 二面叉 -->
        <template v-if="filterForm.sidefork  === 0">
          <el-form-item label="底部拉秤">
            <el-select v-model="filterForm.t_bottomlayer" clearable style="width: 80px">
              <el-option label="无" :value="0" />
              <el-option label="有" :value="1" />
            </el-select>
          </el-form-item>
 
          <el-form-item label="腿布局">
            <el-select v-model="filterForm.t_leglayout" clearable style="width: 80px">
              <el-option label="三条" :value="1" />
              <el-option label="四条" :value="2" />
            </el-select>
          </el-form-item>
        </template>
 
        <!-- 动态字段 - 四面叉 -->
        <template v-else-if="filterForm.sidefork  === 1">
          <el-form-item label="结构类型">
            <el-select v-model="filterForm.f_structure" clearable style="width: 80px">
              <el-option label="A型" value="A" />
              <el-option label="B型" value="B" />
            </el-select>
          </el-form-item>
 
          <el-form-item label="垫块高度(cm)">
            <el-input-number 
              v-model="filterForm.f_blockheight" 
              :min="8" 
              :max="30" 
              controls-position="right" 
              style="width: 100px"
            />
          </el-form-item>
        </template>
 
        <!-- 通用字段 -->
        <el-form-item label="板翼(cm)">
          <el-input-number 
            v-model="filterForm.tf_boardwing"   
            :min="0" 
            :max="20" 
            controls-position="right" 
            style="width: 100px"
          />
        </el-form-item>
 
        <el-form-item label="定制类型">
          <el-select v-model="filterForm.customize"  clearable style="width: 100px">
            <el-option label="二手" :value="0" />
            <el-option label="定制" :value="1" />
          </el-select>
        </el-form-item>
 
        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="resetFilters" :icon="Refresh">
            重置 
          </el-button>
        </el-form-item>
      </el-form>
    </div>
 
    <!-- 数据表格 -->
    <div class="table-card">
      <el-table 
        :data="tableData" 
        v-loading="loading"
        border 
        stripe 
        highlight-current-row 
        style="width: 100%"
      >
        <el-table-column prop="pid" label="产品ID" width="100" sortable align="center" />
        <el-table-column prop="name" label="产品名称" width="120" sortable show-overflow-tooltip />
 
        <el-table-column label="叉型" width="100" align="center">
          <template #default="{row}">
            <el-tag :type="row.sidefork  === 0 ? 'success' : 'primary'">
              {{ row.sidefork  === 0 ? '二面叉' : '四面叉' }}
            </el-tag>
          </template>
        </el-table-column>
 
        <el-table-column label="板材" width="120" align="center">
          <template #default="{row}">
            {{ row.panel_Leg  === 0 ? '板条-原木' : '胶合板-多层板' }}
          </template>
        </el-table-column>
 
        <el-table-column label="定制类型" width="100" align="center">
          <template #default="{row}">
            <el-tag :type="row.customize  === 0 ? 'info' : 'error'">
              {{ row.customize  === 0 ? '二手' : '定制' }}
            </el-tag>
          </template>
        </el-table-column>
 
        <el-table-column label="规格详情" width="200">
          <template #default="{row}">
            <div class="spec-details">
              <template v-if="row.sidefork  === 0">
                <p><span class="label">底部拉秤:</span> {{ row.t_bottomlayer ? '有' : '无' }}</p>
                <p><span class="label">腿布局:</span> {{ getLegLayoutText(row.t_leglayout) }}</p>
              </template>
              <template v-else>
                <p><span class="label">结构类型:</span> {{ row.f_structure || '无' }}</p>
                <p><span class="label">垫块高度:</span> {{ row.f_blockheight }}cm</p>
              </template>
              <p><span class="label">板翼:</span> {{ row.tf_boardwing  }}cm</p>
            </div>
          </template>
        </el-table-column>
 
        <el-table-column prop="price" label="价格(元)" width="120" sortable align="right">
          <template #default="{row}">
            {{ formatPrice(row.price)  }}
          </template>
        </el-table-column>
 
        <el-table-column label="操作" width="90" fixed="right" align="center">
          <template #default="{row}">
            <el-button size="small" @click="handleEdit(row)" :icon="Edit" type="primary">
              编辑
            </el-button>
            <!-- <el-button size="small" type="primary" @click="handleDetail(row)" :icon="View">
              详情
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
 
    <!-- 分页控件 -->
    <div class="pagination-section">
      <el-button 
        :disabled="!hasPrevPage || loading" 
        @click="loadPrevPage"
        v-if="hasPrevPage"
      >
        ← 上一页 
      </el-button>
      
      <el-button 
        :disabled="!hasNextPage || loading" 
        @click="loadNextPage"
        :loading="loading"
      >
        {{ loading ? '加载中...' : '下一页 →' }}
      </el-button>
 
      <span class="page-info" v-if="tableData.length  > 0">
        当前显示 {{ tableData.length  }} 条记录 
        <span v-if="!hasNextPage">- 已加载全部</span>
      </span>
    </div>
 
    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑产品信息" 
      width="50%"
      @closed="resetEditForm"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="120px"
      >
        <el-form-item label="产品ID" prop="pid">
          <el-input v-model="editForm.pid"  disabled />
        </el-form-item>
        
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="editForm.name"  />
        </el-form-item>
        
        <el-form-item label="叉型" prop="sidefork">
          <el-select v-model="editForm.sidefork"  @change="handleEditForkTypeChange">
            <el-option label="二面叉" :value="0" />
            <el-option label="四面叉" :value="1" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="板材类型" prop="panel_Leg">
          <el-select v-model="editForm.panel_Leg"> 
            <el-option label="板条-原木" :value="0" />
            <el-option label="胶合板-多层板" :value="1" />
          </el-select>
        </el-form-item>
        
        <!-- 动态字段 - 二面叉 -->
        <template v-if="editForm.sidefork  === 0">
          <el-form-item label="底部拉秤" prop="t_bottomlayer">
            <el-select v-model="editForm.t_bottomlayer">
              <el-option label="无" :value="0" />
              <el-option label="有" :value="1" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="腿布局" prop="t_leglayout">
            <el-select v-model="editForm.t_leglayout">
              <el-option label="三条" :value="1" />
              <el-option label="四条" :value="2" />
            </el-select>
          </el-form-item>
        </template>
        
        <!-- 动态字段 - 四面叉 -->
        <template v-else>
          <el-form-item label="结构类型" prop="f_structure">
            <el-select v-model="editForm.f_structure">
              <el-option label="A型" value="A" />
              <el-option label="B型" value="B" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="垫块高度(cm)" prop="f_blockheight">
            <el-input-number 
              v-model="editForm.f_blockheight" 
              :min="8" 
              :max="30" 
            />
          </el-form-item>
        </template>
        
        <el-form-item label="板翼(cm)" prop="tf_boardwing">
          <el-input-number 
            v-model="editForm.tf_boardwing"  
            :min="0" 
            :max="20" 
          />
        </el-form-item>
        
        <el-form-item label="价格(元)" prop="price">
          <el-input-number 
            v-model="editForm.price"  
            :min="0" 
            :precision="2" 
          />
        </el-form-item>
        
        <el-form-item label="定制类型" prop="customize">
          <el-select v-model="editForm.customize"> 
            <el-option label="二手" :value="0" />
            <el-option label="定制" :value="1" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark"  type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
 
<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Refresh, Edit, View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { product_ListWithFiltersAPI, product_updateAPI } from '@/api/api'

const router = useRouter()

// 组件状态
const loading = ref(false)
const tableData = ref([])

// 游标分页配置
const pagination = reactive({
  cursor: null, // 当前游标
  nextCursor: null, // 下一页游标
  prevCursors: [], // 历史游标栈，用于上一页
  limit: 10,
  hasMore: true // 是否有更多数据
})

// 计算属性：是否有上一页/下一页
const hasPrevPage = computed(() => pagination.prevCursors.length > 0)
const hasNextPage = computed(() => pagination.hasMore)

// 筛选表单
const filterForm = reactive({
  pid: null,
  name: '',
  sidefork: null,
  panel_Leg: null,
  t_bottomlayer: null,
  t_leglayout: null,
  tf_boardwing: null,
  f_structure: null,
  f_blockheight: null,
  customize: null
})

// 编辑对话框相关 
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  pid: null,
  name: '',
  sidefork: null,
  panel_Leg: null,
  t_bottomlayer: null,
  t_leglayout: null,
  tf_boardwing: null,
  f_structure: null,
  f_blockheight: null,
  price: null,
  customize: null,
  remark: ''
})

// 表单验证规则 
const editFormRules = {
  name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  sidefork: [{ required: true, message: '请选择叉型', trigger: 'change' }],
  panel_Leg: [{ required: true, message: '请选择板材类型', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }]
}

// 初始化加载数据
onMounted(() => {
  fetchProductData()
})

// 构建请求参数
const buildParams = () => {
  const params = {
    cursor: pagination.cursor, // 使用游标而不是页码
    limit: pagination.limit, 
    pid: filterForm.pid, 
    name: filterForm.name, 
    sidefork: filterForm.sidefork, 
    panel_leg: filterForm.panel_Leg, // 注意：后端是 panel_leg，不是 panel_Leg
    t_bottomlayer: filterForm.t_bottomlayer,
    t_leglayout: filterForm.t_leglayout,
    tf_boardwing: filterForm.tf_boardwing, 
    f_structure: filterForm.f_structure,
    f_blockheight: filterForm.f_blockheight,
    customize: filterForm.customize  
  }

  // 移除空值参数 
  Object.keys(params).forEach(key => {
    if (params[key] === null || params[key] === '' || params[key] === undefined) {
      delete params[key]
    }
  })

  return params 
}

// 获取产品数据
const fetchProductData = async () => {
  try {
    loading.value = true
    const params = buildParams()
    
    const res = await product_ListWithFiltersAPI(params)
    
    if (res.code === 200) {
      const data = res.data
      tableData.value = data.data || []
      
      // 游标分页处理
      pagination.nextCursor = data.nextCursor // 假设后端返回 nextCursor
      
      // 判断是否有更多数据
      if (data.hasMore !== undefined) {
        pagination.hasMore = data.hasMore
      } else {
        // 如果没有明确返回 hasMore，根据数据长度判断
        pagination.hasMore = tableData.value.length >= pagination.limit
      }
      
      console.log('分页信息:', {
        cursor: pagination.cursor,
        nextCursor: pagination.nextCursor,
        hasMore: pagination.hasMore,
        prevCursors: pagination.prevCursors,
        dataLength: tableData.value.length
      })
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  } catch (error) {
    ElMessage.error('请求异常: ' + error.message) 
  } finally {
    loading.value = false 
  }
}

// 处理搜索 
const handleSearch = () => {
  // 重置分页状态
  pagination.cursor = null
  pagination.nextCursor = null
  pagination.prevCursors = []
  pagination.hasMore = true
  fetchProductData()
}

// 重置筛选条件 
const resetFilters = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = null
  })
  // 重置分页状态
  pagination.cursor = null
  pagination.nextCursor = null
  pagination.prevCursors = []
  pagination.hasMore = true
  fetchProductData()
}

// 叉型变化处理
const handleForkTypeChange = (value) => {
  if (value === 0) {
    filterForm.f_structure = null
    filterForm.f_blockheight = null 
  } else {
    filterForm.t_bottomlayer = null 
    filterForm.t_leglayout = null 
  }
}

// 分页导航方法
const loadPrevPage = () => {
  if (hasPrevPage.value) {
    // 从历史游标栈中取出上一个游标
    const prevCursor = pagination.prevCursors.pop()
    pagination.cursor = prevCursor
    fetchProductData()
  }
}

const loadNextPage = () => {
  if (hasNextPage.value) {
    // 关键修复：保存当前页的游标到历史栈
    // 这里保存的是当前页的标识，用于返回时使用
    pagination.prevCursors.push(pagination.cursor)
    
    // 设置下一页的游标
    pagination.cursor = pagination.nextCursor
    fetchProductData()
  }
}

// 查看详情
const handleDetail = (row) => {
  router.push(`/product/detail/${row.pid}`) 
}

// 点击编辑按钮 
const handleEdit = (row) => {
  Object.assign(editForm, {
    pid: row.pid, 
    name: row.name, 
    sidefork: row.sidefork, 
    panel_Leg: row.panel_Leg, 
    t_bottomlayer: row.t_bottomlayer,
    t_leglayout: row.t_leglayout,
    tf_boardwing: row.tf_boardwing, 
    f_structure: row.f_structure,
    f_blockheight: row.f_blockheight,
    price: row.price, 
    customize: row.customize, 
    remark: row.remark || ''
  })
  editDialogVisible.value = true 
}

// 编辑表单叉型变化处理 
const handleEditForkTypeChange = (value) => {
  if (value === 0) {
    editForm.f_structure = null
    editForm.f_blockheight = null 
  } else {
    editForm.t_bottomlayer = null 
    editForm.t_leglayout = null 
  }
}

// 提交编辑表单
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate() 
    
    const response = await product_updateAPI(editForm)
    
    if (response.code === 200) {
      ElMessage.success(response.message || '产品更新成功')
      editDialogVisible.value = false 
      
      // 更新本地数据
      const index = tableData.value.findIndex(item => item.pid === editForm.pid) 
      if (index !== -1) {
        tableData.value[index] = { ...tableData.value[index], ...editForm }
      }
    } else {
      ElMessage.error(response?.message || '更新失败')
    }
  } catch (error) {
    console.error('更新出错:', error)
    ElMessage.error(error.message || '请求异常')
  }
}

// 重置编辑表单
const resetEditForm = () => {
  editFormRef.value?.resetFields() 
}

// 辅助方法：格式化价格
const formatPrice = (price) => {
  return price ? Number(price).toFixed(2) : '0.00'
}

// 辅助方法：获取腿布局文本 
const getLegLayoutText = (value) => {
  const map = { 1: '三条', 2: '四条', 0: '无' }
  return map[value] || '未知'
}
</script>
 
<style scoped>
.product-management-container {
  padding: 20px;
  background-color: #f5f7fa;
}
 
.filter-card {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
 
.table-card {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
 
.pagination-container {
  display: flex;
  justify-content: flex-end;
  background: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
 
.spec-details {
  line-height: 1.8;
}
 
.spec-details .label {
  display: inline-block;
  width: 80px;
  color: #909399;
}
 
.el-form-item {
  margin-bottom: 15px;
  margin-right: 15px;
}
</style>